package com.jhmk.springboot;

import com.jhmk.springboot.exception.ParamsException;
import com.jhmk.springboot.model.ResultInfo;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
public class GlobalExceptionHandler {
//Aop 全局异常处理 专门捕获某种类型的异常
    @ExceptionHandler(value = ParamsException.class)
    @ResponseBody
    public ResultInfo resoverParamsException(ParamsException ex){

        ResultInfo info=new ResultInfo();
        info.setCode(500);
        info.setMsg("全局异常捕获");

        return info;
    }
    //处理数据校验抛出的异常
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public ResultInfo resoverBindException(BindException ex){

        ResultInfo info=new ResultInfo();
        info.setCode(500);
        info.setMsg(ex.getBindingResult().getFieldError().getDefaultMessage());
        return info;
    }
}
